package com.atung.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.atung.dao.AdmSchoolDAO;
import com.atung.dao.SchoolUserDAO;
import com.atung.model.AdmSchool;
import com.atung.model.BusSchoolUser;
import com.atung.model.WxLoginDTO;
import com.atung.request.RequestWxRegister;
import com.atung.response.ResponseChangeSchool;
import com.atung.response.ResponseGetAccessToken;
import com.atung.response.ResponseWxLogin;
import com.atung.service.UserLoginService;
import com.atung.tool.Dictionaries;
import com.atung.tool.TemplateTool;
import com.atung.tool.wxUrl.WxUrlTool;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;

@Service
public class UserLoginServiceImpl implements UserLoginService {

//	//获取access_token
//	public static String getAccessTokenURL=" https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPIDS&secret=SECRET";

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;
    
	@Autowired
	private SchoolUserDAO schoolUserDAO;
	@Autowired
	private AdmSchoolDAO admSchoolDAO;
	@Override
	public ResponseWxLogin selectUserAndOpenId(WxLoginDTO  loginMessage)throws Exception {
		// TODO 自动生成的方法存根
		
		System.out.println(stringRedisTemplate.opsForValue().get(Dictionaries.schoolAccessTokenRedisKey));
		BusSchoolUser busSchoolUser=schoolUserDAO.selectUserAndOpenId(loginMessage.getOpenid());
		ResponseWxLogin date=new ResponseWxLogin();
		if(Objects.isNull(busSchoolUser)){
			String accessToken=stringRedisTemplate.opsForValue().get(Dictionaries.schoolAccessTokenRedisKey);
			if(!stringRedisTemplate.hasKey(Dictionaries.schoolAccessTokenRedisKey)){
//				String response=HttpUtil.get(String.format(getAccessTokenURL, appid,secret).toLowerCase());
				//获取accessTokenUrl
				String accessTokenUrl=WxUrlTool.GetAccessToken.replace("APPID", appid).replace("SECRET", secret);
				String response=HttpUtil.get(accessTokenUrl);
				ResponseGetAccessToken  AccessToken=JSONUtil.toBean(response, ResponseGetAccessToken.class);
				accessToken=AccessToken.getAccess_token(); 
				stringRedisTemplate.opsForValue().set(Dictionaries.schoolAccessTokenRedisKey,AccessToken.getAccess_token(),AccessToken.getExpires_in(), TimeUnit.MILLISECONDS);
			}
			String userMessage=HttpUtil.get(String.format(WxUrlTool.GetWxUserMessage,accessToken,loginMessage.getOpenid()).toLowerCase());
			JSONObject jsonObject=JSONObject.parseObject(userMessage);
			BusSchoolUser insertUser=new BusSchoolUser();
			if (null != jsonObject) {
				try {
					insertUser.setWxName(jsonObject.getString("nickname"));
					insertUser.setWxPhoto(jsonObject.getString("headimgurl"));
//					insertUser.setUserSex(Integer.parseInt(jsonObject.getString("sex")));
				} catch (JSONException e) {
				
					// 获取token失败
					throw new Exception("ERR INSERTANDTOKEN USERMESSAGE");
				}
			}
			insertUser.setOpenId(loginMessage.getOpenid());
			insertUser.setCreationTime(new Date(System.currentTimeMillis()).toInstant());
			Boolean insertResult=schoolUserDAO.insertUser(insertUser);
			if(!insertResult){
				//新增用户失败
				throw new Exception("ERR INSERT USERMESSAGE");
			}
		
			date.setOpenid(loginMessage.getOpenid());
			date.setIsRegister(true);
			return date;
		}
		date.setOpenid(busSchoolUser.getOpenId());
		date.setIsRegister(false);
//		if(Objects.isNull(busSchoolUser.getSchoolId())){
//			date.setIsRegister(true);
//		}
		return date;
	}

	@Override
	public void updatetUserAndOpenId(RequestWxRegister request) {
		// TODO 自动生成的方法存根
		
		BusSchoolUser updateUser=new BusSchoolUser();
		BeanUtil.copyProperties(request, updateUser);
		updateUser.setModificationTime(new Date(System.currentTimeMillis()).toInstant());
		schoolUserDAO.updatetUserAndOpenId(updateUser);
	}

	@Override
	public List<ResponseChangeSchool> selectSchoolBylonAndlat(String lon, String lat) {
		// TODO 自动生成的方法存根
		List<AdmSchool> admSchoolList=new ArrayList<>();
		for(int scope=1;scope<50;scope++ ){
			admSchoolList =admSchoolDAO.selectSchoolBylonAndlat(lon,lat,scope);
			if(admSchoolList.size()!=0){
				continue;
			}
		}
		List<ResponseChangeSchool>changeSchoolList=new ArrayList<>();
		for(AdmSchool admSchool: admSchoolList){
			ResponseChangeSchool changeSchool=new ResponseChangeSchool();
			BeanUtil.copyProperties(admSchool, changeSchool);
			changeSchool.setSchoolId(admSchool.getId());
			changeSchoolList.add(changeSchool);
		}
		return changeSchoolList;
	}
	
	
//	public static void main(String[] args) {
//		
//		String userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
//		
//		String accessTokenUrl=WxUrlTool.GetAccessToken.replace("APPID", "wx5b232372414ebba4").replace("SECRET", "0af31ce449aa2683336c004cfa211610");
//		String response=HttpUtil.get(accessTokenUrl);
//		ResponseGetAccessToken  AccessToken=JSONUtil.toBean(response, ResponseGetAccessToken.class);
//
//		ResponseGetAccessToken  Access=JSONUtil.toBean(response, ResponseGetAccessToken.class);
//		
//		System.out.println(Access.toString());
//		//XIXI
//
//
//		String requestUrl = userinfo_url.replace("ACCESS_TOKEN",Access.getAccess_token()).replace("OPENID","oM1yx4mcT2ApDbIZUKMUGMl65_vQ");
//		String responseM=HttpUtil.get(requestUrl);
//		System.out.println("----"+requestUrl);
//		System.out.println("----"+responseM);
//		String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token"+Access.getAccess_token()+"&openid=oM1yx4mcT2ApDbIZUKMUGMl65_vQ&lang=zh_CN";
//		String responses=HttpUtil.get(url);
//
//		System.out.println("+++"+url);
//		System.out.println("+++"+responses);
//	}
//	

}
